package com.airbnb.mvrx.sample.features.clickread.views

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.widget.FrameLayout
import com.airbnb.epoxy.TypedEpoxyController
import com.airbnb.mvrx.sample.Utils
import com.airbnb.mvrx.sample.core.UpApplication
import com.example.mvrxstudy.R
import com.yt.ytdeep.client.dto.ClickReadPage

class CRContentView : FrameLayout {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val mCarousel: PagerCarousel
    private val mController: PageContentController
    private var curPosition: Int = 0
    private var scrollListener: SnappingRecyclerView.OnViewSelectedListener? = null

    init {
        inflate(context, R.layout.view_content_cr, this)
        mCarousel = findViewById(R.id.recycler_view)
        mController = PageContentController()
        mCarousel.setController(mController)
        mCarousel.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (recyclerView is PagerCarousel) {
                    val snapView = recyclerView.snapHelper.findSnapView(recyclerView.layoutManager)
                    val position = recyclerView.layoutManager.getPosition(snapView)
                    if (curPosition != position) {
                        curPosition = position
                        if (scrollListener != null) {
                            scrollListener!!.onSelected(recyclerView, position)
                        }
                    }
                }
            }
        })
    }

    fun setContent(pages: List<ClickReadPage>) {
        mController.setData(pages)
    }

    fun setPosition(position: Int) {
        mCarousel.scrollToPosition(position)
    }

    fun setOnScrollListener(listener: SnappingRecyclerView.OnViewSelectedListener?) {
        scrollListener = listener
    }

    class PageContentController : TypedEpoxyController<List<ClickReadPage>>() {
        override fun buildModels(data: List<ClickReadPage>?) {
            data!!.forEachIndexed { index, each ->
                cRContentItem {
                    id(each.id)
                    image(Utils.imageUrlFromResId(UpApplication.getApp().BASE_URL, each.imgResId, each.imgResSign))
                    position(index)
                }
            }
        }

    }

}